<template>
    <div>
        <div class="page-header">
            <CustomTitle :title="route.meta.title" />
            <el-space>
                <el-button type="primary" @click="save()">保存</el-button>
                <el-button type="primary" plain @click="close">取消</el-button>
            </el-space>
        </div>
        <el-scrollbar max-height="calc(100vh - 200px)">
            <div class="form">
                <el-form label-width="auto" :model="form" ref="formRef" :rules="rules">
                    <el-form-item label="模板名称" prop="warrantyName">
                        <el-input placeholder="请输入模板名称" v-model="form.warrantyName" />
                    </el-form-item>
                    <el-form-item label="质保状态">
                        <el-radio-group v-model="form.warrantyStatus">
                            <el-radio :value="0">生效中</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="质保开始日期">
                        <el-radio-group v-model="form.warrantyBeginType">
                            <el-radio :value="0">订单合同支付后开始</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="质保时限" prop="warrantyTime">
                        <el-input placeholder="请输入质保时间周期“按月计算" v-model="form.warrantyTime">
                            <template #suffix>
                                <span>月</span>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="dividing"></div>
            <div class="editor">
                <Toolbar :editor="editorRef" style="border-bottom:1px solid #E2E8F0;" :defaultConfig="toolbarConfig"
                    :mode="mode" />
                <Editor style="height: 500px; overflow-y: hidden;" v-model="form.warrantyContent"
                    :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
            </div>
            <div class="remark">
                <el-form>
                    <el-form-item label="备注">
                        <el-input v-model="form.remark" :rows="2" type="textarea" placeholder="请填写内容说明，最多不超多200字。" />
                    </el-form-item>
                </el-form>
            </div>
        </el-scrollbar>
        <el-dialog v-model="colseVisible" width="400" center align-center :show-close="false">
            <div class="sure">
                <div>
                    <el-icon>
                        <Warning />
                    </el-icon>
                </div>
                <span>取消后，您设置的商品质保信息将被清除，请保存后在离开，确认要继续离开吗？</span>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="colseVisible = false">取消</el-button>
                    <el-button type="primary" @click="router.push('/stencil/warranty')">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import CustomTitle from "@/components/CustomTitle/index.vue";
import { shallowRef, ref, onBeforeUnmount, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css';
import useMultipartOssStore from "@/store/modules/multipartOssStore";
import { getTempDetail, addTemplate, editTemplate } from "@/apis/mallConfig/warranty";
import { ElMessage } from "element-plus";


const multipartOss = useMultipartOssStore();
const router = useRouter();
const route = useRoute();
const colseVisible = ref(false)

const form = ref({
    warrantyStatus: 0,
    warrantyBeginType: 0
})
const formRef = ref(null)
const editorRef = shallowRef();
const toolbarConfig = {
    excludeKeys: ['group-video', 'fullScreen'],
}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            async customUpload(file, insertFn) {
                const fileName = `crm/${file.name}`;
                multipartOss.submit(fileName, file).then(async () => {
                    await multipartOss.setACL(fileName, 'public-read')
                    const url = await multipartOss.signatureUrl(fileName);
                    insertFn(url);
                })

            }
        }
    }
}
const validator = (rule, value, callback) => {
    const regex = /^\d{1,10}$/;
    if (regex.test(value)) {
        callback()
    } else {
        callback(new Error('请输入10位以内的正整数'))
    }
}
const rules = {
    warrantyName: [
        { required: true, message: '请输入模板名称', trigger: 'blur' },
        { max: 20, message:"请输入20位以内的字符",trigger: 'blur'}
    ],
    warrantyTime: [
        { required: true, message: '请输入质保时限', trigger: 'blur' },
        { validator, trigger: 'blur' }
    ]
}
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
const close = () => {
    colseVisible.value = true;
}
const save = () => {
    if (!formRef.value) return;
    const callback = (res) => {
        if (res.code == 200) {
            ElMessage.success('保存成功');
            router.push('/stencil/warranty')
        }
    }
    formRef.value.validate(async (value) => {
        if (value) {
            if (route.query.warrantyId) {
                const res = await editTemplate({ ...form.value, warrantyId: route.query.warrantyId });
                callback(res)
            } else {
                const res = await addTemplate(form.value);
                callback(res)
            }
        }
    })

}

const getDetail = async () => {
    if (route.query.warrantyId) {
        const res = await getTempDetail({ warrantyId: route.query.warrantyId });
        const { warrantyName, warrantyTime, remark, warrantyContent, warrantyId } = res.data;
        form.value = { ...form.value, warrantyName, warrantyTime, remark, warrantyContent, warrantyId }
    }
}

onMounted(() => {
    getDetail();
})
onBeforeUnmount(() => {
    // 销毁编辑器
    const editor = editorRef.value;
    if (editor == null) return
    editor.destroy()
})
</script>

<style lang="scss" scoped>
@import 'index'
</style>